package com.zlll.winner.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zlll.winner.business.service.weixin.IWxToolsService;
import com.zlll.winner.common.WXCore;
import com.zlll.winner.util.HttpClientUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/wx")
@Api(description = "微信api相关接口")
public class WxAPIAction {

    protected transient final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Reference(version = "${dubbo.consumer.version}")
    private IWxToolsService wxToolsService;

    @PostMapping("decrypt")
    @ResponseBody
    @ApiOperation(value = "获取decrypt")
    public Object decrypt(
            @ApiParam(
                    name = "params",
                    value = "{\n" +
                            "  \"appId\": \"1\",\n" +
                            "  \"encryptedData\": \"xxx\",\n" +
                            "  \"sessionKey\": \"aes\",\n" +
                            "  \"iv\": \"a\"\n" +
                            "}",
                    required = true)
            @RequestBody Map params) {
        JSONObject jsonObject = new JSONObject(params);
        String result = WXCore.decrypt(wxToolsService.getAppId(), jsonObject.getString("encryptedData"), jsonObject.getString("sessionKey"), jsonObject.getString("iv"));
        logger.error("微信接口decrypt 参数：" + JSON.toJSONString(params)+"\n结果："+result);
        return JSON.parse(result);
    }

    @PostMapping("jscode2session")
    @ResponseBody
    @ApiOperation(value = "获取jscode2session")
    public Object getSessionKey(@RequestBody Map params){
        params.put("appid",wxToolsService.getAppId());
        params.put("secret",wxToolsService.getSecret());
        String result = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session",params);
        logger.error("微信接口jscode2session 参数：" + JSON.toJSONString(params)+"\n结果："+result);

        return JSON.parse(result);
    }
}
